// 老师布置作业
import express from 'express';
import pool from "../../importantApi/db_connection.js";

const router = express.Router();
router.post("/", async (req, res) => {
    const data = req.body;
    if (!data.createtime) {
        let date = new Date()
        const year = date.getFullYear()
        const month = date.getMonth() + 1
        const day = date.getDate()
        const hour = date.getHours()
        const minute = date.getMinutes()
        data.createtime = `${year}-${String(month).padStart(2,'0')}-${String(day).padStart(2,'0')} ${String(hour).padStart(2,'0')}:${String(minute).padStart(2,'0')}`
    }
    try {
        // 根据多个班级，找出每个班级对应的班级名
        let [result] = await pool.query(`
            select u.user_name as teacher_name,
                   c.class_id,
                   c.class_name
            from userinfo u
                     left join classinfo c
                               on c.class_id in (${data.class_id})
            where u.user_id = '${data.teacher_id}'
        `)
        // 转换为二维数组
        const values = result.map(item => [
            item.teacher_id = data.teacher_id,
            item.teacher_name,
            item.title = data.title,
            item.content = data.content,
            item.subject = data.subject,
            item.class_id,
            item.class_name,
            item.createtime = data.createtime,
            item.deadline = data.deadline,
            item.image_list = data.image_list,
            item.recorder_list = data.recorder_list,
            item.video_list = data.video_list,
            item.file_list = data.file_list,
            item.work_type = data.work_type
        ])
        // 批量插入函数
        const chunkSize = 1000
        const chunks = chunkArray(values, chunkSize)
        for (const chunk of chunks) {
            const sql = `
                insert into homework (teacher_id, teacher_name, title, content, subject,
                                      class_id, class_name, createtime, deadline, image_list,
                                      recorder_list, video_list, file_list,work_type)
                values ?
            `
            await pool.query(sql, [chunk])
        }
        return res.status(200).json({
            code: 200,
            msg: "作业布置成功"
        })
    } catch (err) {
        console.log(err)
        res.status(500).json({
            code: 500,
            error: err,
            msg: "布置作业错误：server error"
        })
    }
})

// 分块函数
function chunkArray(arr, chunkSize) {
    const chunks = [];
    for (let i = 0; i < arr.length; i += chunkSize) {
        chunks.push(arr.slice(i, i + chunkSize));
    }
    return chunks;
}

export default router;